package xml;

import game.GameState;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

/**
 * Methods to help with XML stuff
 * @author Mark Kelly
 * @date March 30, 2010
 * @version 4.0
 * 
 * @author Trevor Bastian
 * @date March 31, 2010
 * @version 4.0
 * 
 * @since version 4.0
 *
 */

public class XMLHandler {

	public static void saveToFile(File file, XMLizeable obj, String rootName) {
		Document doc = saveToDocument(obj, rootName);
		saveDocumentToFile(file, doc);
	}
	
	public static void saveDocumentToFile(File file, Document doc) {
		XMLSerializer serializer = null;
			
		
		//print
		OutputFormat format = new OutputFormat(doc);
		format.setIndenting(true);
		
		//to generate a file output use fileoutputstream
		try {
			serializer = new XMLSerializer(
			new FileOutputStream(file), format);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		try {
			serializer.serialize(doc);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static Document saveToDocument(XMLizeable obj, String rootName) {
		Document doc;
    	Element root;
		//get an instance of factory
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = null;
		
		//get an instance of builder
		try {
			db = dbf.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}

		//create an instance of DOM
		doc = db.newDocument();
		
		root = doc.createElement(rootName);
		doc.appendChild(root);
		
		Element child = obj.toXML(doc);
		root.appendChild(child);
		
		return doc;
	}
	
	public static GameState loadGameStateFromDoc(Document doc) {
		GameState temp = null;

		Element root = doc.getDocumentElement();
		NodeList elements = root.getElementsByTagName(game.GameState.class.getName());
		
		temp = GameState.importFromXML((Element)elements.item(0));
		
		return temp;
	}
	
	public static GameState loadGameStateFromFile(File file) {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		Document doc = null;
		
		try {
			doc = dbf.newDocumentBuilder().parse(file.getName());
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
		
		return loadGameStateFromDoc(doc);
	}
}
